package com.ashafa.server;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.envjson.JSONArray;
import org.envjson.JSONException;
import org.envjson.JSONObject;

import javax.servlet.ServletException;

public class Routing {
	
	public Routing(){
		
	}
	
	public RoutingResult route(String uri, JSONArray urlsArray, String contextPath ) throws ServletException{
		
		int j = 0;
		String view = null;
		String uriTokensJsonString = null;
		
		String uriToMatch = (uri.replaceAll("^"+contextPath,"") + "/").replaceAll("/{2,}", "/");
		
		try
		{
			while(j < urlsArray.length() && urlsArray.getJSONObject(j).keys().hasNext())
			{
				String viewKey =  (String)urlsArray.getJSONObject(j).keys().next() ;
				String viewKeyPattern = ("/" + viewKey + "/").replaceAll("/", "//").replaceAll("\\*{2,}", "*").replaceAll("\\*", "/.+/").replaceAll("/<([^/]+?)>/", "/(?:$1::)?([^/]+)/");
				viewKeyPattern = viewKeyPattern.replaceAll("/{2,}", "/");
				
				String[] urlSlugKeys = viewKeyPattern.split("::");
				
				Pattern pattern = Pattern.compile("^" + viewKeyPattern + "$");
			    Matcher matcher = pattern.matcher(uriToMatch);
			    
			    if(matcher.find())
			    {
			    	view =(String)urlsArray.getJSONObject(j).getString(viewKey);
			    	HashMap urlSlugs = new HashMap();
			    	
			    	for (int i = 1; i <= matcher.groupCount(); i++)
			    	{
			    		urlSlugs.put(urlSlugKeys[i-1].replaceAll("^.+:", ""), matcher.group(i));
			    	}
			    	uri = uri.replaceAll("(.+)/$", "$1");
			    	uriTokensJsonString = (new JSONObject(urlSlugs)).toString();
			    	break;
			    }
			    j++;
			}
		} catch(JSONException e) {
			throw new ServletException(e);
		}
		
		return new RoutingResult(view, uriTokensJsonString);
		
	}
}
